package com.company.netty;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

public class Client {
    public static void main(String[] args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioSocketChannel.class)
             .handler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 protected void initChannel(SocketChannel ch) {
                     ch.pipeline()
                       .addLast(new LengthFieldBasedFrameDecoder(1024, 4, 4))
                       .addLast(new MessageDecoder())
                       .addLast(new MessageEncoder())
                       .addLast(new SimpleChannelInboundHandler<CustomMessage>() {
                           @Override
                           protected void channelRead0(ChannelHandlerContext ctx, CustomMessage msg) {
                               System.out.println("收到响应: " + msg.getContent());
                           }
                       });
                 }
             });
            
            // 建立连接
            Channel channel = b.connect("localhost", 8080).sync().channel();
            
            // 发送请求（带超时控制）
            CustomMessage request = new CustomMessage(1, "Request-1");
            ChannelFuture future = channel.writeAndFlush(request);
            
            // 等待写入完成（超时3秒）
            if(!future.await(3, TimeUnit.SECONDS)) {
                throw new TimeoutException("写入超时");
            }
            
            Thread.sleep(60000); // 保持连接
        } finally {
            group.shutdownGracefully();
        }
    }
}
